Skip to content

Lrp for review - #900

Open
Nimanui wants to merge 23 commits into
sunlabuiuc:masterfrom
Nimanui:lrp-for-review
Open

Nimanui wants to merge 23 commits into
sunlabuiuc:masterfrom
Nimanui:lrp-for-review

Conversation

@Nimanui

@Nimanui Nimanui commented Mar 20, 2026

Copy link
Copy Markdown
Contributor

Looking to add some alpha, beta, and epsilon LRP saliency options run across a few different models (both the MIMIC IV stagenet and the chest x-ray CNN)
Original implementation is based off of https://arxiv.org/abs/1604.00825 and is very vibey so I'm expecting some comments
I may prune down the example options a bit as this ended up a bit bloated, and I'll need to add some more documentation

Comment on lines +405 to +431
if mode == "binary":
# Binary logits have shape [B] or [B, 1].
# target_class_idx=1 (positive) → use logit as-is.
# target_class_idx=0 (negative) → negate so LRP attributes for the
# "not-positive" direction (relevance conservation still holds for -logit).
if target_class_idx is not None:
idx = (
target_class_idx
if isinstance(target_class_idx, int)
else int(target_class_idx.item())
)
if idx == 0:
return -logits
return logits
if mode in ("multiclass", "multilabel"):
if target_class_idx is None:
target_class_idx = torch.argmax(logits, dim=-1)
elif not isinstance(target_class_idx, torch.Tensor):
target_class_idx = torch.tensor(
target_class_idx, device=logits.device
)
batch_size = logits.size(0)
output_relevance = torch.zeros_like(logits)
output_relevance[range(batch_size), target_class_idx] = logits[
range(batch_size), target_class_idx
]
return output_relevance

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The target_class_index hanlding has been unified in #926. With the following semantics

  1. binary will always have targret_class_index 0
  2. the attribution is always towards positive, and up to the evaluator to flip the sign for negative class contribution
  3. if not specified, both multi-class and multi-label uses argmax

Comment thread pyhealth/interpret/methods/lrp.py Resolved
Comment thread pyhealth/interpret/methods/lrp.py Resolved
Comment thread pyhealth/interpret/methods/lrp_base.py Resolved
@github-actions

github-actions Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 76.19% (22726 / 29828 lines)

Modified file Coverage Lines
pyhealth/interpret/methods/__init__.py 100.00% 18 / 18
pyhealth/interpret/methods/basic_gradient.py 93.59% 73 / 78
pyhealth/interpret/methods/lrp.py 96.60% 369 / 382
pyhealth/interpret/methods/lrp_base.py 100.00% 304 / 304
pyhealth/interpret/methods/saliency_visualization.py 100.00% 165 / 165
pyhealth/metrics/interpretability/base.py 73.25% 167 / 228

Workflow run · ab5604f

@Logiquo Logiquo added the status: automatic The PR will go through automatic review process. label Oct 26, 2026
@Logiquo

Logiquo commented Oct 26, 2026

Copy link
Copy Markdown
Collaborator

/review

@github-actions github-actions Bot removed the status: automatic The PR will go through automatic review process. label Oct 26, 2026
@github-actions github-actions Bot added the status: manual Pending maintainer's review label Oct 26, 2026
@Nimanui

Nimanui commented Oct 26, 2026 via email

Copy link
Copy Markdown
Contributor Author

@Logiquo

Logiquo commented Oct 26, 2026

Copy link
Copy Markdown
Collaborator

I'll look into this and see if it can be reduced a bit

i don't think your PR has 300 different files. maybe simply due to outdated branch. i think you can try to merge the latest master and see.

@Nimanui

Nimanui commented Oct 27, 2026 via email

Copy link
Copy Markdown
Contributor Author

@Nimanui

Nimanui commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

/review

@Logiquo Logiquo added status: automatic The PR will go through automatic review process. and removed status: manual Pending maintainer's review labels Nov 2, 2026
@Logiquo

Logiquo commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator

/review

@github-actions github-actions Bot added status: manual Pending maintainer's review and removed status: automatic The PR will go through automatic review process. labels Nov 2, 2026
@Nimanui

Nimanui commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Still no luck, I still suspect it's the python notebooks causing the glut of extra lines. Do you think it's worth separating those out and trying again? I could put those in a different PR.

@jhnwu3

jhnwu3 commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator

Yes thats an existing limitation of the auto review system, but that would probably resolve the context issues.

Nimanui and others added 2 commits November 2, 2026 23:08
Keeps this PR within the AI review size limit: the example scripts and
notebooks move to a follow-up PR, test_lrp_simple.py is folded into
test_lrp.py (its one unique check, target-class sensitivity on StageNet,
is kept), unused pytest fixtures are removed, and tests are added for
lrp_base handlers, CNN/residual LRP paths, SaliencyVisualizer and the
mean ablation baseline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Nimanui

Nimanui commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

Turns out it was definitely the pics. Had the AI do an analysis with the character limitation in mind and it should be below the limit now. I'll have to do a follow-up PR with the notebook examples though. I've also added a few more tests to improve the test coverage.

@Nimanui

Nimanui commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

In general any PR with pics will probably be punted to manual due to the limitations.

@Nimanui

Nimanui commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

@Logiquo Can you try setting this to automatic one more time and see if removing the notebooks worked.

@Logiquo Logiquo added status: automatic The PR will go through automatic review process. and removed status: manual Pending maintainer's review labels Nov 6, 2026
@Nimanui

Nimanui commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed commit ab5604f


For complete working examples, see:

- ``examples/interpretability/lrp_stagenet_synthetic.py`` — self-contained run on synthetic data, no external dataset required

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[medium] Docs reference example files that do not exist

The Quick Start section lists three example files: examples/interpretability/lrp_stagenet_synthetic.py, examples/interpretability/lrp_stagenet_mimic4.py and examples/ChestXray-Classification-ResNet-with-Saliency.ipynb. None of them exists in the repository, and the PR does not add them. Either add the examples in this PR or remove these references (and the matching note in the PR description about pruning examples) so the docs do not point to missing files.

img = img.squeeze(-1)

# Ensure values are in reasonable range for display
if img.max() > 1.0 and img.max() <= 255.0:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[medium] Normalized RGB images are blackened by a spurious /255 rescale

_process_image divides any image whose max is in (1, 255] by 255. Images normalized with ImageNet statistics (max about 2.2 to 2.6) match this condition, so an RGB image is divided by 255 and imshow renders it nearly black. The existing BasicGradientSaliencyMaps.visualize_saliency_map now routes through this function, so its output regresses for the normalized inputs its docstring recommends. Rescale only when the dtype is uint8 or the data is known to be in [0, 255], and add a test with ImageNet-normalized input.

import torch


class SaliencyVisualizer:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[medium] SaliencyVisualizer duplicates existing interpret utilities

pyhealth/interpret/utils.py already provides normalize_attribution (line 227, including a percentile method) and visualize_image_attr (line 272, which normalizes the image and attribution and builds the overlay). SaliencyVisualizer._normalize_saliency and the overlay logic in plot_saliency_overlay reimplement these. Reuse normalize_attribution and visualize_image_attr (or extend them) instead of adding a parallel visualization stack with five plotting methods and two module-level helpers.

Comment thread docs/api/interpret.rst
interpret/pyhealth.interpret.methods.chefer
interpret/pyhealth.interpret.methods.attention_rollout
interpret/pyhealth.interpret.methods.deeplift
interpret/pyhealth.interpret.methods.lrp

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[medium] Existing API doc pages removed from the toctree without explanation

The toctree drops interpret/pyhealth.interpret.methods.ig_gim, ensemble, baseline and base_interpreter. Their RST files still exist under docs/api/interpret/, so Sphinx will report them as not included in any toctree, and the public API for those classes disappears from the rendered docs. The PR description does not mention this. Restore those entries, or move the removal into a separate, explained change.

# ============================================================================


def create_default_registry() -> LRPHandlerRegistry:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] create_default_registry and check_tensor_validity are unused in production

create_default_registry duplicates the handler list in LayerwiseRelevancePropagation.init (lrp.py), and the two lists already differ because only the factory registers EmbeddingLRPHandler. check_tensor_validity (line 61) is never called outside its doctest. Keep one registration path and delete the unused helpers, or call them from the interpreter.

unittest.main()


class TestMeanAblationBaseline(unittest.TestCase):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] New test class is defined after the main block

TestMeanAblationBaseline is placed after the if name == 'main': unittest.main() block at line 538. Running the file as a script calls unittest.main() before the class exists, so these regression tests only run under pytest. Move the class above the main guard.

Comment thread tests/core/test_lrp.py
relative_diff = abs(total_relevance - logit) / max(abs(logit), 1e-6)
print(f"Relative difference: {relative_diff:.2%}")

self.assertLess(relative_diff, 3.0,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] Conservation tests accept errors of up to 300% and 150%

test_relevance_sums_to_output allows relative error below 3.0, and the StageNet conservation test (line 1190) allows 1.5. Neither would catch a sign flip or a missing residual term, so the conservation property is effectively untested for the model paths. The linear-layer test in test_lrp_base.py does check conservation exactly and is the stronger check. Assert a tight bound on a model whose logit dominates its biases, or on the exact linear handler, and keep the looser bound as a documented smoke test.

print("[RemovalBasedMetric] WARNING: Unknown classifier")
print(f" - Mode detected: {mode}")

def _mean_baseline(self, x: torch.Tensor) -> torch.Tensor:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] Metrics fix is not described and the mean-ablation docs are stale

_mean_baseline changes what Comprehensiveness and Sufficiency return for 'mean' ablation at batch_size=1, which was previously a silent no-op. The fix is sound, but the PR description does not mention it. The evaluator and base docstrings (base.py line 43) still say 'feature mean across batch', which no longer holds at batch_size=1. Split this into its own PR or describe it, and update the docstrings.

at construction and dispatches each layer through it, so support for a custom
layer can be added without subclassing the interpreter::

lrp._registry.register(MyLayerHandler())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] Docs advertise the private _registry attribute as an extension point

The docs tell users to call lrp._registry.register(...) to add a custom layer handler. Documenting a leading-underscore attribute as public API makes it hard to change later. Expose a public register_handler method on LayerwiseRelevancePropagation and document that instead.

@github-actions github-actions Bot added status: manual Pending maintainer's review and removed status: automatic The PR will go through automatic review process. labels Nov 7, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI Review

suggestion: need change
decision: human review

Thank you for this contribution. It adds alpha-beta and epsilon LRP attribution with per-layer handlers, a shared saliency visualizer, and tests that cover the new LRP code well. It is close, but a few things need fixing first.

A maintainer will also take a look. The change modifies the shared RemovalBasedMetric base class: mean ablation at batch_size=1 now returns different scores than before, which previously came back as a silent 0.0. That counts as touching core code.

To get this merged:

  1. The LRP doc page references example files that aren't in the PR: examples/interpretability/lrp_stagenet_synthetic.py, examples/interpretability/lrp_stagenet_mimic4.py, and examples/ChestXray-Classification-ResNet-with-Saliency.ipynb. Either add them or remove the references.
  2. docs/api/interpret.rst drops ig_gim, ensemble, baseline and base_interpreter from the toctree, which leaves their existing pages orphaned. Please restore them unless the removal is intentional, and explain it in the description if it is.
  3. SaliencyVisualizer._process_image divides any image whose max is in (1, 255] by 255. ImageNet-normalized inputs, which the docs recommend, would then render nearly black in the existing visualize_saliency_map. Please make this rescaling more careful, for example only for uint8 dtype or a max above 1.5 together with non-negative values.
  4. saliency_visualization.py appears to overlap with the existing normalize_attribution and visualize_image_attr helpers in pyhealth/interpret/utils.py. Please reuse them or explain why a new module is needed.

Optional suggestions:

  • Mention the metrics mean-ablation fix in the PR description, and update the _mean_baseline docstring.
  • TestMeanAblationBaseline is placed after the if __name__ == "__main__" block in test_interp_metrics.py. Move it above the block so it runs when the file is run as a script.
  • The conservation assertions (relative error below 3.0 and 1.5) are very loose and would not catch regressions.
  • create_default_registry and check_tensor_validity are unused in production code, and the docs advertise the private lrp._registry as an extension point. Consider a public API for registering handlers.

Coverage: the new files are at 96–100%, above the 80% bar. The whole repository is at 76.19%, above the 60% bar. metrics/interpretability/base.py is at 73.25%, below the 80% file-level guideline, though that is mostly pre-existing code.

Reviewed commit ab5604f

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: manual Pending maintainer's review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants